package com.atguigu.daijia.customer.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.atguigu.daijia.common.code.RedisCache;
import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.customer.client.CustomerInfoFeignClient;
import com.atguigu.daijia.customer.service.CustomerService;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@RequiredArgsConstructor
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerServiceImpl implements CustomerService {

    private final CustomerInfoFeignClient client;
    private final RedisCache redisCache;


    /**
     * login 登录并生成token
     *
     * @param code
     * @return java.lang.String
     * @author wgp
     * @date 2024/8/9 11:16
     */
    @Override
    public String login(String code) {
        //远程调用解析openid
        Result<Long> loginResult = client.login(code);
        if (loginResult.checkFail()) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        Long customerId = loginResult.getData();
        if (customerId == null) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        //生成Token
        String token = IdUtil.fastSimpleUUID();
        redisCache.setCustomerLoginObject(token, customerId);
        return token;
    }

    @Override
    public CustomerLoginVo getCustomerLoginInfo(Long userId) {
        Result<CustomerLoginVo> customerLoginVoResult = client.getCustomerInfo(userId);
        if (customerLoginVoResult.checkFail()) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        return customerLoginVoResult.getData();
    }
}
